import {PrismaClient} from '@prisma/client'
import {format} from 'date-fns'
import {isArray, isNull, isPlainObject} from 'lodash'

let prisma: PrismaClient | null = null

if (isNull(prisma)) {
  prisma = new PrismaClient()
}

const dwPrisma = prisma.$extends({
  query: {
    async $allOperations({args, query}) {
      const result = await query(args)
      if (isPlainObject(result)) {
        if (result.createTime) {
          result.createTime = format(result.createTime, 'yyyy-MM-dd HH:mm:ss')
        }
        if (result.updateTime) {
          result.updateTime = format(result.updateTime, 'yyyy-MM-dd HH:mm:ss')
        }
      }
      if (isArray(result)) {
        result.map(e => {
          if (e.createTime) {
            e.createTime = format(e.createTime, 'yyyy-MM-dd HH:mm:ss')
          }
          if (e.updateTime) {
            e.updateTime = format(e.updateTime, 'yyyy-MM-dd HH:mm:ss')
          }
          return e
        })
      }
      // 在这里查看结果
      return result
    },
  },
})

export default dwPrisma

export type DwPrismaClient = typeof dwPrisma
